package com.virgo.demo.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.virgo.common.entity.IResponse;
import com.virgo.common.entity.IUserToken;
import com.virgo.login.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

	@Autowired
	private TokenService tokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
		IUserToken iUserToken = tokenService.get(false);
		if (ObjectUtils.isEmpty(iUserToken)) {
			response.setContentType("application/json;charset=utf-8");
			response.getWriter().println(JSON.toJSONString(IResponse.logout()));
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

	}
}